package com.guiwu.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guiwu.entity.Category;
import com.guiwu.entity.Item;
import com.guiwu.mapper.ItemMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> {

    @Autowired
    private CategoryService categoryService;

    /**
     * 获取用户所有物品
     */
    public List<Item> getAllItemsByUser(Long userId) {
        return this.list(new LambdaQueryWrapper<Item>().eq(Item::getUserId, userId).orderByDesc(Item::getCreatedAt));
    }

    /**
     * 按分类获取物品
     */
    public List<Item> getItemsByCategory(Long userId, Long categoryId) {
        return this.list(new LambdaQueryWrapper<Item>()
                .eq(Item::getUserId, userId)
                .eq(Item::getCategoryId, categoryId)
                .orderByDesc(Item::getCreatedAt));
    }

    /**
     * 按名称模糊搜索
     */
    public List<Item> searchItems(Long userId, String keyword) {
        return this.list(new LambdaQueryWrapper<Item>()
                .eq(Item::getUserId, userId)
                .like(Item::getName, keyword)
                .orderByDesc(Item::getCreatedAt));
    }

    /**
     * 计算用户总资产
     */
    public BigDecimal getTotalAssets(Long userId) {
        List<Item> items = getAllItemsByUser(userId);
        return items.stream()
                .map(Item::getPrice)
                .filter(price -> price != null)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 计算用户平均日均价格
     */
    public BigDecimal getAverageDailyPrice(Long userId) {
        List<Item> items = getAllItemsByUser(userId);
        if (items.isEmpty()) {
            return BigDecimal.ZERO;
        }

        BigDecimal totalDailyPrice = items.stream()
                .map(Item::getDailyPrice)
                .filter(dailyPrice -> dailyPrice != null)
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        return totalDailyPrice.divide(BigDecimal.valueOf(items.size()), 2, java.math.RoundingMode.HALF_UP);
    }

    /**
     * 获取用户使用的分类列表
     */
    public List<Category> getCategoriesByUser(Long userId) {
        // 获取用户物品中使用的分类ID
        List<Long> categoryIds = this.list(new LambdaQueryWrapper<Item>()
                .eq(Item::getUserId, userId)
                .select(Item::getCategoryId))
                .stream()
                .map(Item::getCategoryId)
                .distinct()
                .collect(Collectors.toList());

        if (categoryIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 根据分类ID获取分类信息
        return categoryService.listByIds(categoryIds);
    }

    /**
     * 获取用户物品统计信息
     */
    public ItemStatistics getItemStatistics(Long userId) {
        List<Item> items = getAllItemsByUser(userId);

        ItemStatistics statistics = new ItemStatistics();
        statistics.setTotalItems(items.size());
        statistics.setTotalAssets(getTotalAssets(userId));
        statistics.setAverageDailyPrice(getAverageDailyPrice(userId));
        statistics.setCategories(getCategoriesByUser(userId));

        return statistics;
    }

    /**
     * 物品统计信息内部类
     */
    public static class ItemStatistics {
        private int totalItems;
        private BigDecimal totalAssets;
        private BigDecimal averageDailyPrice;
        private List<Category> categories;

        // Getters and Setters
        public int getTotalItems() { return totalItems; }
        public void setTotalItems(int totalItems) { this.totalItems = totalItems; }

        public BigDecimal getTotalAssets() { return totalAssets; }
        public void setTotalAssets(BigDecimal totalAssets) { this.totalAssets = totalAssets; }

        public BigDecimal getAverageDailyPrice() { return averageDailyPrice; }
        public void setAverageDailyPrice(BigDecimal averageDailyPrice) { this.averageDailyPrice = averageDailyPrice; }

        public List<Category> getCategories() { return categories; }
        public void setCategories(List<Category> categories) { this.categories = categories; }
    }
}